package com.znyj.cloud.device.task;

import com.znyj.cloud.chain.util.CheckUtil;
import com.znyj.cloud.device.constant.SysConstant;
import com.znyj.cloud.device.executor.ReportExecutorService;
import com.znyj.cloud.device.pack.OnlineDeviceInfo;
import io.netty.channel.ChannelHandlerContext;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by gaoliwei02 on 17/6/3.
 */
@Component
public class OfflineDeviceMapping {
    private static final Logger logger = Logger.getLogger(OfflineDeviceMapping.class);

    @Resource
    private ReportExecutorService reportExecutorService;

    public void deviceOffLine(ChannelHandlerContext ctx) {

        List<OnlineDeviceInfo> onlineDeviceInfoList = OnlineDeviceInfoMapping.getODIByChannel(ctx);
        if (onlineDeviceInfoList.size() == 1) {
            String offdev = onlineDeviceInfoList.get(0).getDeviceId();
            OnlineDeviceInfoMapping.removeAndCloseCtx(offdev);
            reportExecutorService.executeOffline(offdev);
            logger.error(CheckUtil.monitorReport(SysConstant.ERROR_CODE.OFFLINE_DEV, "IP:" + ctx.channel().remoteAddress().toString(), Long.parseLong(offdev)));
        } else if (onlineDeviceInfoList.size() > 1) {
            for (int i = 0; i < onlineDeviceInfoList.size(); i++) {
                String offdev = onlineDeviceInfoList.get(i).getDeviceId();
                OnlineDeviceInfoMapping.removeAndCloseCtx(offdev);
                reportExecutorService.executeOffline(offdev);
                logger.error(CheckUtil.monitorReport(SysConstant.ERROR_CODE.OFFLINE_MULT_DEV, "IP:" + onlineDeviceInfoList.get(i).getCtx().channel().remoteAddress().toString(), Long.parseLong(offdev)));
            }
        } else {
            logger.error(CheckUtil.monitorReport(SysConstant.ERROR_CODE.OFFLINE_NO_DEV, "IP:" + ctx.channel().remoteAddress().toString(), 0));
        }
    }
}
